<?php
/*
 * @Author       : lovefc
 * @Date         : 2021-06-21 09:53:41
 * @LastEditTime : 2021-06-21 14:01:09
 */

namespace Main\Model;

// 控制器基类
use FC\Model\BaseModel;

class commentator extends BaseModel
{

    function __construct()
    {
		// 数据库配置类型,默认为Mysql
		//$this->db_type = 'Mysql';		
		// 数据库配置链接名称,默认为default
		//$this->db_config_name = 'default';
        $this->rules = [
            // 常用的封装验证
            'email'    => ['邮箱', [$this, 'check_email']],
            // 类方法验证
            'nickname'   => '必填',

            'imgurl'  => [$this, 'get_avatar_url'],

            'homeurl' => [[$this, 'improve_url'], '网址']
        ];

        $this->avatarDir = PATH['NOW'] . '/Public/avatar/';
        // 执行父类
        parent::__construct();
    }

    /**
     * 获取单一的值
     *
     * @return void
     */
    public function getOnlyValue(array $datas = [], $fleid = '')
    {
        $where  = $this->filterValue($datas);
        $res   = $this->db->where($where)->limit(1)->value($fleid);
        if ($res) {
            return $res;
        } else {
            return null;
        }
    }

    // 获取头像
    public function get_avatar_url()
    {
        return $this->avatar_url;
    }

    // 完善网址
    public function improve_url($str = '')
    {
        if (!preg_match('/^http:\/\//', $str)) {
            $str = "http://" . $str;
        }
        return $str;
    }

    // 验证邮箱
    public function check_email($email = '')
    {

        $url = $this->GetGravatar($email);

        $this->ext = $ext = \FC\File::suffix($url);

        $path = $this->avatarDir . $email . '.jpg';

        \FC\File::remote($url, $path, true);

        $this->avatar_url  = '/Public/avatar/' . $email . '.jpg';

        return $email;
    }
	
    // 获取gravatar邮箱地址，来源官方
    public function GetGravatar($email, $s = 80, $d = 'mm', $r = 'g')
    {
        $url = 'https://www.gravatar.com/avatar/';
        $url = 'http://fdn.geekzu.org/avatar/'; // 自建的代理缓存
        $url .= md5(strtolower(trim($email)));
        $url .= "?s=$s&d=$d&r=$r";
        return $url;
    }
}
